#include "StratChooser.h"
using namespace BWAPI;
using namespace std;
#define NUM_STEPS 1

StratChooser::StratChooser(void)
{

}

void StratChooser::setup()
{
	generator.setEnemy(StarUtil::getEnemyTypes());
	allyUnits = StarUtil::getSelfUnitTypes();
	generator.addunits(allyUnits);
	done = false;
	ready = false;
	first = true;
	currentStrat = new StrategyGen(generator.getNextStrat());
	battle = new BattleSimulator(currentStrat,&comp);
}
StratChooser::~StratChooser(void)
{
	delete battle;
	delete currentStrat;
}

bool StratChooser::isNotDone()
{
	return !done;
}

void StratChooser::nextStep()
{
		if(!((*battle).isDone()))
			(*battle).step();
		else if(!done)
			reset();
}

bool StratChooser::currentSimDone()
{
	return (*battle).isDone();
}

void StratChooser::resolve()
{
	while(!done)
	{
		(*battle).resolve();
		reset();
	}	
}


void StratChooser::reset()
{
	Result current;
	if((*battle).redWon())//player won
		current.setResult((*battle).getRemainingUnits(true));
	else// oppenent won
	{
		current.setResult((*battle).getRemainingUnits(false));
		current.lost();
	}
	//If current startegy did better the local best
	if(first ||best.isBetter(current))
	{	
		first = false;
		best = current;
		bestStrat = *currentStrat;
	}
	// if there are more strategies to test
	if(generator.isMore())
	{
		delete currentStrat;
		delete battle;
		currentStrat = new StrategyGen(generator.getNextStrat());
		battle = new BattleSimulator(currentStrat,&comp);
	}
	else
	{
		done = true;
	}
}
StrategyGen StratChooser::getBestStrat()
{
	return bestStrat;	
}